<?php
/**
 * Created by PhpStorm.
 * User: ly
 * Date: 2017/2/16
 * Time: 16:29
 */

namespace App\Http\Controllers;

use App\Student;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Request;
use Illuminate\Support\Facades\Redirect;

use JPush\Client as JPush;
class StudentController extends Controller
{

    public function dbbase()
    {

       //增加数据
        /*$result = DB::insert("insert into la_student(name,age) value(?,?)",['catty','20']);
        if($result){
             $students = DB::select('select * from la_student');
            echo "新增成功";
            var_dump($students);
        }else{
            return "插入失败";
        }*/

        //更改数据
        /*$result = DB::update("update la_student set age = ? where name = ?",['5','tom']);
        if($result){
            $students = DB::select('select * from la_student');
            echo "更新成功";
            var_dump($students);
        }else{
            return "更新失败";
        }*/

        //删除数据
        /*$students = DB::delete('delete from la_student where id > ?',[3]);
        if($students){
            $students = DB::select('select * from la_student');
            echo "删除成功";
            var_dump($students);
        }else{
            return "删除失败";
        }*/

        //查询数据
         $students = DB::select('select * from la_student where id < ?',[4]);
        dd($students);

    }

    //使用查询构造器——增
    public function query_add()
    {
        DB::table('student')->insert([
            ['name'=>'name1','age'=>20],
            ['name'=>'name2','age'=>21]
        ]);

        $students = DB::select('select * from la_student');
        dd($students);
    }
    //使用查询构造器——改
    public function query_edit()
    {
        $student = DB::table('student');

         /*$student->where('id',5)
            ->update(['age'=>30]);*/
        //自增长
        //$student->where('id',5)->increment('age',3);
        //
        $student->where('id',5)->decrement('age',3,['name'=>'imooc']);

        $students = DB::select('select * from la_student where id=5');
        dd($students);
    }
    //使用查询构造器——删
    public function query_del()
    {
        $student = DB::table('student');
        $student->where('id','<=',5)->delete();
        $students = DB::select('select * from la_student');
        var_dump($students);
    }
    //使用查询构造器——查
    public function query_query()
    {
        $student = DB::table('student');
        //获取全部数据
        //$students = $student->get();
        //获取第一条
        //$students = $student->orderBy('id','desc')->first();
        //按条件获取数据
        //$students = $student->where('id','<=',5)->get();

        //$students = $student->whereRaw('id <= ? and age > ?',[7,22])->get();

        //返回指定的单个字段
        //$students = $student->whereRaw('id <= ? and age > ?',[7,22])->pluck('name');

        //返回指定的单个字段,可指定键值
        //$students = $student->whereRaw('id <= ? and age > ?',[7,22])->lists('name','id');

        //返回指定的多个字段,可指定键值
        //$students = $student->whereRaw('id <= ? and age > ?',[7,22])->select('name','id')->get();


        //指定返回的条数,每次查询指定条数，直到数据结束或者遇到false
        $student->chunk(2,function($stu){
            var_dump($stu);

            return false;
        });



        //var_dump($students);
    }
    //使用查询构造器——聚合函数
    public function query_juhe()
    {
        $student = DB::table('student');
        $count = $student->count();
        $max = $student->max('age');
        $min = $student->min('age');
        $avg = $student->avg('age');

        echo '总人数：'.$count;
        echo '<br/>';
        echo '最大年龄：'.$max;
        echo '<br/>';
        echo '最小年龄：'.$min;
        echo '<br/>';
        echo '平均年龄：'.$avg;
        echo '<br/>';

    }

    //使用orm进行数据库查询
    public function orm(){
        //显示全部
        //$students = Student::all();

        //查找一条
        //$students = Student::find(6);

        //根据主键查询，查询不到返回异常
        $students = Student::findOrFail(6);


        //$students = Student::find(6);

        dd($students);
    }

    //查询构造器使用orm进行数据库查询
    public function query_orm(){
        //查全部
//        $students = Student::get();

        //查第一条
        /*$students = Student::where('id','<=',6)
            ->orderBy('age','desc')
            ->first();*/
        //是用聚合函数
        $students = Student::count();

        dd($students);
    }

    //使用orm进行新增数据
    public function orm_add(){
        //使用save

        /*$student = new Student();
        $student->name = 'newTome';
        $student->age = '20';
        $student->age = '20';
        $student->save();*/

        //使用create方法新增数据
        /*$student = Student::create([
            'name'=> 'newMooc','age'=>'21'
        ]);*/

        //有则查看，无则创建
       /* $student = Student::firstOrCreate([
            'name'=> 'newMoocs','age'=>'21'
        ]);*/
        //$students = Student::orderBy('id','desc')->first();

        //有则查看，无则创建实例，保存需要save
        $student = Student::firstOrNew([
            'name'=> 'newMoocss'
        ]);
        $student->save();
        dd($student);
    }

    //使用orm进行修改数据,并自动维护update时间戳
    public function orm_edit()
    {
        //更新指定单条
        /*$student = Student::find(19);
        $student->name = 'kitty';
        $student->save();*/

        //按条件更新多条
        $student = Student::where('id','>','17')
        ->update(
            ['age'=>33]
        );
        $student = Student::get();
        dd($student);
    }

    //使用orm进行删除数据
    public function orm_del()
    {
        //通过模型删除
        /*$student = Student::find(19);
        $student->delete();*/

        //通过主键删除
        $student = Student::destroy(18);

        //条件删除，增加where条件
        $student = Student::get();
        dd($student);
    }

    //在视图中渲染数据
    public function section(){
        $name = 'imooc';
        //$student = Student::get();
        $student = [];
        return view('Student.section',[
            'name'=>$name,
            'title'=>"这是真正的标题",
            'student'=>$student
        ]);
    }

    public function url(){
        return "这个链接正确";
    }

    //获取请求数据，包括get,post,session,serve
    public function request(Request $request)
    {
        //1.取值
        /*echo "我的名字是：" . $request->input('name','默认值');
        $request->has('name');*/
        //dd($request->all('name'));

        //2.判断请求类型
        if($request->isMethod('GET')){
            echo 'is get request'.'<br>';
        }
        if($request->ajax()){
            echo 'is ajax request';
        }else{
            echo 'not is ajax request'.'<br>';
        }
        //判断请求的路由
        if($request->is('student/*')){
            echo 'is student 下的方法'.$request->url();
        }else{
            echo 'not student 下的方法'.'<br>';
        }

        //获取当前url
        $request->url;



    }

    public function session1(Request $request)
    {
        //1.HTTP request session()
        /*$request->session()->put('key1','val1');
        echo $request->session()->get('key1');*/

        //2.session()，使用辅助函数
        /*session()->get('key2','val2');
        echo session()->get('key2');*/

        //3.session，使用session类

        /*Session::put('key3','val3');
        echo Session::get('key3','default');*/

        //4.存入数组到session
        Session::put(['key3'=>'val3']);

        //5.存入数组到一个键值（形成多维数组）
        /*Session::push('studet','tom');
        Session::push('studet','kitty');
        print_r(Session::get('studet','default')) ;*/

        //取完就删除，使用pull
        //print_r(Session::pull('studet','default')) ;

        //取出所有session值
//        var_dump(Session::all());

        //判断是否存在某key
//        Session::has('key1');

        //删除某session
        Session::forget('key1');

        //清空全部session
        Session::flush();

        //暂存数据，使用一次后即销毁
        Session::flash();
    }
    public function session2(Request $request)
    {
        //return 'this is sessin2';
        return Session::get('message','暂无数据');
    }

    public function response()
    {
        $data = [
            'name'=>'米子',
            'title'=>"这是真正的标题",
            'student'=>'student'
        ];
        //var_dump($data);
        //json格式化数据
        //return response()->json($data);

        //重定向
        return redirect('session2')->with('message','我是快闪数据');

        //返回上一页面
        //return redirect()->back();
    }
    //中间件的使用：1.编写中间件规则，2.注册中间件，3.路有种使用中间件
    //活动前页面
    public function pro_activity()
    {
        echo '互动马上开始，敬请期待！';
    }
    //活动进行中页面1
    public function ing1_activity()
    {
        echo '互动已开始，抓紧抢购！';
    }
    //活动进行中页面2
    public function ing2_activity()
    {
        echo '互动已开始，抓紧抢购2！';
    }
    public function form_add(){
        return view('Student.form_add');
    }
    //表单新增
    public function form_add_save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:255',
            'age' => 'required|numeric',
            'sex' => 'required|numeric'
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 最长255个字符',
            'numeric'=>':attribute 必须为数字'
        ],[
            'name'=>'姓名',
            'age'=>'年龄',
            'sex'=>'性别'
        ]);
//var_dump($request->sex);die;
//测试提交功能
        $result = Student::create([
            'name'=>$request->get('name'),
            'age'=>$request->get('age'),
            'sex'=>20
        ]);
        if($result)
        {
            return redirect('student/form')->with('success','新建成功！');
        }else{
            return redirect()->back()->withInput()->with('error','新建失败！');
        }
    }

    public function form_del($id)
    {
        $student = Student::find($id);
        if($student->delete()){
            return redirect('student/form')->with('success','删除成功！');
        }else{
            return redirect()->back()->withInput()->with('error','删除失败！');
        }
    }

    public function form()
    {
        //查全部
        $students = Student::get();
        return view('Student.form',[
            'students'=>$students
        ]);
    }

    /**
     *jpush 极光推送
     * @author   J.K.
     * @time     sj
     * @version  V1.0
     */
    public function jpush()
    {
        $app_key = '884b38f2775a4294f599f8c2';
        $master_secret = '1c03afae13b99145d02371a6';
        $client = new JPush($app_key, $master_secret);

        $rel = $client->push()
            ->setPlatform('all')
            ->addTag(array('3'))//发送给分组为3的观众
            //->addAllAudience()//发送给所有观众
            ->setNotificationAlert('祝你3.8节快乐！')
            ->send();
        if($rel){
            echo '发送成功！';
        }else{
            echo '发送失败！';
        }
    }

    public function form_detail($id)
    {

        $student = Student::find($id);
        return view('Student.form_detail',[
            'student'=>$student
        ]);
    }

    public function form_edit($id)
    {
        $student = Student::find($id);
        return view('Student.form_edit',[
            'student'=>$student
        ]);
    }

    public function form_save(Request $request,$id)
    {
        $validator = $this->validate($request, [
            'name' => 'required|max:255',
            'age' => 'required|numeric',
            'sex' => 'required|numeric'
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 最长255个字符',
            'numeric'=>':attribute 必须为整数'
        ],[
            'name'=>'姓名',
            'age'=>'年龄',
            'sex'=>'性别'
        ]);

        $student = Student::find($id);

        $student->name = $request->get('name');
        $student->age = $request->get('age');
        $student->sex = $request->get('sex');

        if($student->save())
        {
            return redirect('student/form')->with('success','编辑成功！');
        }else{
            return redirect()->back()->withInput()->with('error','编辑失败！');
        }

    }


}